# 数据库迁移脚本
# 用于手动执行数据库迁移

param(
    [string]$ConnectionString = "Host=localhost;Port=5432;Database=authservice;Username=postgres;Password=postgres",
    [string]$Action = "up",
    [long]$Version = 0
)

Write-Host "开始执行数据库迁移..." -ForegroundColor Green
Write-Host "连接字符串: $ConnectionString" -ForegroundColor Yellow
Write-Host "操作: $Action" -ForegroundColor Yellow

# 切换到项目目录
$projectPath = Join-Path $PSScriptRoot "..\AuthService.Api"
Set-Location $projectPath

try {
    # 安装FluentMigrator工具（如果未安装）
    Write-Host "检查FluentMigrator工具..." -ForegroundColor Blue
    $toolCheck = dotnet tool list -g | Select-String "fluentmigrator.dotnet.cli"
    if (-not $toolCheck) {
        Write-Host "安装FluentMigrator工具..." -ForegroundColor Blue
        dotnet tool install -g FluentMigrator.DotNet.Cli
    }

    # 构建项目
    Write-Host "构建项目..." -ForegroundColor Blue
    dotnet build --configuration Release

    if ($LASTEXITCODE -ne 0) {
        throw "项目构建失败"
    }

    # 执行迁移
    $assemblyPath = "bin\Release\net9.0\AuthService.Infrastructure.dll"
    
    switch ($Action.ToLower()) {
        "up" {
            Write-Host "执行向上迁移..." -ForegroundColor Blue
            if ($Version -eq 0) {
                dotnet fm migrate -p postgres -c $ConnectionString -a $assemblyPath
            } else {
                dotnet fm migrate -p postgres -c $ConnectionString -a $assemblyPath --version $Version
            }
        }
        "down" {
            if ($Version -eq 0) {
                throw "回滚操作必须指定版本号"
            }
            Write-Host "执行回滚到版本 $Version..." -ForegroundColor Blue
            dotnet fm rollback -p postgres -c $ConnectionString -a $assemblyPath --version $Version
        }
        "list" {
            Write-Host "列出所有迁移..." -ForegroundColor Blue
            dotnet fm list migrations -p postgres -c $ConnectionString -a $assemblyPath
        }
        "validate" {
            Write-Host "验证迁移..." -ForegroundColor Blue
            dotnet fm validate -p postgres -c $ConnectionString -a $assemblyPath
        }
        default {
            throw "不支持的操作: $Action。支持的操作: up, down, list, validate"
        }
    }

    if ($LASTEXITCODE -eq 0) {
        Write-Host "数据库迁移执行成功!" -ForegroundColor Green
    } else {
        throw "数据库迁移执行失败"
    }
}
catch {
    Write-Host "错误: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host "迁移完成!" -ForegroundColor Green
